import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/base/AbsLifecycleState.dart';
import 'package:photo_frame/dialog/edit_member_dialog.dart';
import 'package:photo_frame/mixin/auto_hide_loading.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/net/model/member_model.dart';
import 'package:photo_frame/provider/users_provider.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/user/user_manager.dart';
import 'package:photo_frame/utils/a_logger.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';

class MemberListPage extends StatefulWidget {
  String? _frameId;

  MemberListPage(Map<String, dynamic>? args, {super.key}) {
    _frameId = args?["frameId"] ?? "";
  }

  @override
  State<StatefulWidget> createState() {
    return MemberListState();
  }
}

class MemberListState extends AbsLifecycleState<MemberListPage>
    with AutoHideLoading {
  GlobalKey<RefreshIndicatorState> _refreshIndicatorStateKey = GlobalKey();

  MemberListViewModel vm = MemberListViewModel();

  @override
  void onResume() {
    super.onResume();
    _refreshIndicatorStateKey.currentState?.show();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    vm.init(context, widget._frameId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: commonAppBar(
          AppLocalizationsWrapper.instance.unwrap(context).memberListTitle,
          onBack: () {
        ARouter.instance.pagePop(arguments: {"data": vm._list});
      }, actions: [
        CupertinoButton(
          padding: EdgeInsets.zero,
          onPressed: () async {
            final res = await showDialog<MemberModel>(
                context: context,
                builder: (BuildContext context) =>
                    EditMemberDialog({"frameId": widget._frameId}));
            // if (res != null) {
            //   _refreshIndicatorStateKey.currentState?.show();
            // }
          },
          child: actionTextWidget(
              AppLocalizationsWrapper.instance.unwrap(context).addMember),
        )
      ]),
      body: RefreshIndicator(
        key: _refreshIndicatorStateKey,
        onRefresh: () => vm.fetch(context),
        child: Center(
          child: ChangeNotifierProvider(
            create: (context) => vm,
            child: Builder(builder: (context) {
              return Padding(
                padding: const EdgeInsets.only(top: 10),
                child: Selector<MemberListViewModel, List<MemberModel>>(
                  builder: (BuildContext context, List<MemberModel> value,
                      Widget? child) {
                    return ListView.separated(
                        itemBuilder: (context, index) => _calendarItemWidget(
                            context, index, vm._list[index]),
                        separatorBuilder: (context, index) => SizedBox(
                              height: 11,
                            ),
                        itemCount: vm._list.length);
                  },
                  shouldRebuild: (n1, n2) => n1 != n2,
                  selector: (_, vm) {
                    return vm._list;
                  },
                ),
              );
            }),
          ),
        ),
      ),
    );
  }

  Widget _calendarItemWidget(
      BuildContext context, int index, MemberModel item) {
    return Container(
      height: 66,
      margin: EdgeInsets.symmetric(horizontal: 12.5),
      child: Card(
        color: Colors.white,
        margin: EdgeInsets.zero,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
        child: Row(
          children: [
            SizedBox(width: 12.5),
            Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Color(item.color ?? 0xff4B90FF).withOpacity(1),
                shape: BoxShape.circle,
              ),
              width: 26,
              height: 26,
              child: Text(
                item.name?.isNotEmpty == true ? item.name!.substring(0, 1) : "",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 13,
                    fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(width: 9),
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Visibility(
                    visible: item.name?.isNotEmpty == true,
                    child: Text(
                      item.name ?? "",
                      style: TextStyle(
                        color: Color(0xff000000),
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Visibility(
                    visible: item.email?.isNotEmpty == true,
                    child: Text(
                      item.email ?? "",
                      style: TextStyle(
                        color: Color(0xff999999),
                        fontSize: 14,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(width: 5),
            Visibility(
              visible: item.type == 1 || item.type == 2,
              child: CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () async {
                  final res = await showDialog<MemberModel>(
                      context: context,
                      builder: (BuildContext context) => EditMemberDialog({
                            "frameId": widget._frameId,
                            "member": item.toMap()
                          }));
                  // if (res != null) {
                  //   _refreshIndicatorStateKey.currentState?.show();
                  // }
                },
                child: Container(
                  width: 52.5,
                  height: 27,
                  decoration: BoxDecoration(
                      color: Color(0xffEAECEE),
                      borderRadius: BorderRadius.circular(13.5)),
                  margin: EdgeInsets.only(right: 9.5),
                  child: Align(
                    child: Text(
                        textAlign: TextAlign.center,
                        AppLocalizationsWrapper.instance
                            .unwrap(context)
                            .memberEdit,
                        style:
                            TextStyle(color: Color(0xff555555), fontSize: 12),
                        strutStyle: StrutStyle(forceStrutHeight: true)),
                  ),
                ),
              ),
            ),
            Visibility(
              visible: item.type == 2,
              child: CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  vm.delete(context, item);
                },
                child: Container(
                  width: 52.5,
                  height: 27,
                  decoration: BoxDecoration(
                      color: Color(0xffEAECEE),
                      borderRadius: BorderRadius.circular(13.5)),
                  margin: EdgeInsets.only(right: 9.5),
                  child: Align(
                    child: Text(
                      textAlign: TextAlign.center,
                      AppLocalizationsWrapper.instance
                          .unwrap(context)
                          .memberDelete,
                      style: TextStyle(color: Color(0xff555555), fontSize: 12),
                      strutStyle: StrutStyle(forceStrutHeight: true),
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class MemberListViewModel extends ChangeNotifier {
  late UsersViewModel _usersViewModel;
  late String? _frameId;
  List<MemberModel> _list = [];
  late VoidCallback usersCallback;

  init(BuildContext context, String? frameId) {
    _frameId = frameId;
    _usersViewModel = context.read<UsersViewModel>();
    _usersViewModel.addListener(usersCallback = () {

      _list = _usersViewModel.members.filterByFrameId(_frameId);
      notifyListeners();
      ALogger.e("usersCallback  : ${_list.length}");
    });
  }

  @override
  void dispose() {
    super.dispose();
    _usersViewModel.removeListener(usersCallback);
  }

  fetch(BuildContext context) async {
    await _usersViewModel.fetch(_frameId ?? "");
  }

  delete(BuildContext context, MemberModel memberModel) async {
    await EasyLoading.show(
      maskType: EasyLoadingMaskType.black,
    );
    await _usersViewModel.delete(memberModel.id ?? -1);
    await EasyLoading.dismiss();
  }
}
